#region (c) 2014 THN Solutions LLC. - All rights reserved
/*
Simplified BSD License (BSD)
THN HTTP Stack Library
Copyright (c) 2014, THN Solutions LLC. ( www.ThnSolutions.com )
Author: Nguyễn, M. Hải                 ( www.Minh-Hai.com     )
All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright notice, this 
      list of conditions and the following disclaimer.

    * Redistributions in binary form must reproduce the above copyright notice, 
      this list of conditions and the following disclaimer in the documentation 
      and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
POSSIBILITY OF SUCH DAMAGE.
*/
#endregion

#region Record of Change
//             							CHANGE HISTORY
// -------------------------------------------------------------------------------------
// |   DATE    | DEVELOPER  | DESCRIPTION                                              |
// -------------------------------------------------------------------------------------
// | 12-May-13 | HaiNM      | First creation.                                          |
// -------------------------------------------------------------------------------------
//
#endregion

#region Record of Audit
//             							REVIEW HISTORY
// -------------------------------------------------------------------------------------
// |   DATE    | REVIEWER   | NOTES                                                    |
// -------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------
//
#endregion

#region Using directives
using System;

using Thn;
using Thn.Collections;
#endregion

namespace Thn.Net.Http
{
    /// <summary>
    /// This helper class is used to break down a URL path to individual elements.
    /// <para>Note: this class assumes the URL is already decoded.</para>
    /// </summary>
#if DEBUG || TESTING
    public
#else
    public
#endif
 class UrlParser
    {
        #region Constants
        const char QueryMaker = '?';
        const char ParameterSeparator = '&';
        const char ParameterValueSeparator = '=';
        const char PathSeparator = '/';
        #endregion
        #region Fields
        #endregion

        #region Properties

        #region Hostname
        private string mHostname;
        /// <summary>
        /// Gets reference to the host name portion (without port).
        /// </summary>
        public string Hostname
        {
            get { return mHostname; }
        }
        #endregion

        #region Port
        private int mPort;
        /// <summary>
        /// Gets reference to the host port portion (without host name).
        /// </summary>
        public int Port
        {
            get { return mPort; }
        }
        #endregion

        #region Parts
        private StringList mParts = new StringList();
        /// <summary>
        /// Gets reference to list of part that make up the URL main path (without host and query portion).
        /// </summary>
        public StringList Parts
        {
            get { return mParts; }
        }
        #endregion

        #region Query
        private UrlQuery mQuery = new UrlQuery();
        /// <summary>
        /// Gets reference to the parameters present in the query string (if available)
        /// </summary>
        public UrlQuery Query
        {
            get { return mQuery; }
        }
        #endregion

        #endregion

        #region Reset
        void Reset()
        {
            mHostname = string.Empty;
            mPort = -1;
            mParts.Clear();
            mQuery.Clear();
        }
        #endregion

        #region Parse
        /// <summary>
        /// Process the provided URL and break it down to basic elements.
        /// <para>Note: this method assume the URL is already decoded.</para>
        /// </summary>
        /// <param name="url">Decoded URL string to be processed.</param>
        public void Parse(string url)
        {
            Reset();

            int idx = url.IndexOf(QueryMaker);
            if (idx > 0)
            {
                #region Has query -> process it

                string query = url.Substring(idx + 1);
                string[] pairs = query.Split(ParameterSeparator);
                if (pairs != null && pairs.Length > 0)
                {
                    string pair;
                    int length = pairs.Length;
                    string[] items;
                    for (int i = 0; i < length; i++)
                    {
                        pair = pairs[i];
                        items = pair.Split(ParameterValueSeparator);
                        if (items != null && items.Length == 2)
                        {
                            mQuery.Add(items[0], items[1]);
                        }
                        else
                        {
                            #region Invalid format
                            throw new Exception("Invalid URL query format");
                            #endregion
                        }
                    }
                }
                #region Defensive tracing
                else
                {
                    //no parameters -> skip
                }
                #endregion

                //remove query portion from url
                url = url.Substring(0, idx);
                #endregion
            }

            string[] parts = url.Split(PathSeparator);
            if (parts != null && parts.Length > 0)
            {
                int length = parts.Length;
                idx = 0;

                //detect if there is a host portion
                if (length > 2)
                {
                    string firstPart = parts[0].ToLower();
                    if (firstPart == "http:" || firstPart == "https:")
                    {
                        string host = parts[2];
                        idx = host.IndexOf(':');
                        if (idx > 0)
                        {
                            #region Has port portion

                            mHostname = host.Substring(0, idx);
                            mPort = int.Parse(host.Substring(idx + 1));

                            #endregion
                        }
                        else
                        {
                            #region No port portion
                            mHostname = host;
                            #endregion
                        }

                        //move index to after host portion
                        idx = 3;
                    }
                }

                //proceed with other parts
                if (idx < length)
                {
                    for (int i = idx; i < length; i++)
                    {
                        if (!string.IsNullOrEmpty(parts[i]))
                        {
                            mParts.Add(parts[i]);
                        }
                    }
                }
                #region Defensive tracing
                else
                {
                    //there are no more parts left
                }
                #endregion
            }
            #region Defensive tracing
            else
            {
                //no parts, skip
            }
            #endregion

        }
        #endregion

        #region Constructors
        /// <summary>
        /// Create a new instance.
        /// </summary>
        public UrlParser()
            : base()
        { }
        #endregion
    }
}
